Random¶

🖌 random¶

NOTES

  • For each example, demonstrate how running the code again yields different results

random.choice()¶

In [31]:
import random

fruits = ['pear','mango','banana','strawberry','kumquat']
selection = random.choice(fruits)
print(selection)
pear

random.randint()¶

In [48]:
import random

print(random.randint(1, 10))
3

NOTES

  • Note that random.randint() can return the boundary numbers
    • so, the return number is anything including and between the arguments.

random.random()¶

In [142]:
print(random.random())
0.5543172281869808

If you need a random float between 0 and 100, just scale the random number:

In [160]:
print(random.random() * 100)
55.191740700033634

random.sample()¶

In [161]:
name = 'Tom Marvolo Riddle'
In [177]:
print(random.sample(name, 2))
['o', 'r']
In [187]:
print(random.sample(name, 10))
['m', ' ', 'R', 'o', 'l', 'o', 'T', 'd', 'o', 'i']
In [264]:
print(''.join(random.sample(name, len(name))))
mdiRoMrooveT d lal

🖌 Shuffle¶

random.sample can be used to get a random sample from a collection.

If you sample all the items in the collection, you essentially get a shuffled version of the data.

In [265]:
import random

def shuffle(string):
    """
    Use random.sample to get the letters in the string in a random order.
    Then join the letters together with the empty string.
    """
    shuffled_letters = random.sample(string, len(string))
    return ''.join(shuffled_letters)
In [288]:
shuffle('12345')
Out[288]:
'24513'
In [303]:
shuffle('CS110')
Out[303]:
'011CS'

🖌 Random events at some frequency¶

apples.py¶

🧑🏼‍🎨 Umm...¶

Write a program that takes a frequency (a number between 0 and 1) and a phrase as commandline arguments.

Randomly inject "umm" into a given sentence at the given frequency and print the result.

umm.py¶

NOTES

  • Draw it out!
    • Sentence -> words -> words with umm -> sentence
python umm.py 0.2 'So, I've been meaning to ask, will you go out on a date with me?'

👨🏻‍🎨 Random¶

  • 2-player guessing game
  • Bit: fill world with random colors
  • Bit: random walk to target

Key Ideas¶

  • random
    • choice
    • randint
    • random
    • sample
  • Shuffling strings using random.sample
  • Random events at some frequency